package com.kk.demo.unsface.two.unsafeList2;

import org.apache.lucene.util.RamUsageEstimator;

import com.kk.demo.unsface.two.unsafelist.UnsafeHelper;

import sun.misc.Unsafe;

public class UnsafeUtil {
    private static Unsafe unsafe;

    public static Unsafe getUnsafe() {
        if (unsafe == null) {
            unsafe = UnsafeHelper.getUnsafe();
        }
        return unsafe;
    }

    public static long getAddress(Object target) {
        Object objArray[] = new Object[1];
        objArray[0] = target;

        long arrayOffset = getUnsafe().arrayBaseOffset(Object[].class);
        long value = 0L;

        if (8 == RamUsageEstimator.NUM_BYTES_OBJECT_REF) {
            value = getUnsafe().getLong(objArray, arrayOffset);
        } else {
            value = normalize(getUnsafe().getInt(objArray, arrayOffset));
            if (8 == getUnsafe().addressSize()) {
                value = value << 3;
            }
        }
        return value;
    }

    private static long normalize(int value) {
        if (value >= 0) {
            return value;
        }
        return value & 0xFFFFFFFFL;
    }

}
